package com.atguigu.lease.web.app.service.impl;


import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exceptions.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.rmi.dgc.Lease;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private Client client;

    @Autowired
    private UserInfoService userInfoService;

    @Override
    public void sendCode(String phone) throws Exception {
        //给我手机号 我发验证码
        //手机号码是不是空或空串
        if (StringUtils.isNullOrEmpty(phone)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        //要把生成的验证码保存到redis中，键是手机号，值为验证码
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;

        //public static final Integer APP_LOGIN_CODE_RESEND_TIME_SEC = 60;//约定短信发送间隔时间 60
        //public static final Integer APP_LOGIN_CODE_TTL_SEC = 60 * 10; //数据库的短信验证码的有效时间 600
        Boolean hasKey = redisTemplate.hasKey(key);
        //检查的前提 key有效的!
        //检查发送的间隔时间是否大于APP_LOGIN_CODE_RESEND_TIME_SEC ||  500  540  550
        // 有效的总时间(600)  -  获取剩余的有效时间  < 间隔时间显示 60  抛异常
        //60秒后才可以重发，但可以存在redis600秒，也就是剩余时间小于540秒就可以重发了。
        if (hasKey) {
            //剩余时间
            Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
            if (RedisConstant.APP_LOGIN_CODE_TTL_SEC - expire < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC) {
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
            //使用随机数生成验证码
            Random random = new Random();
            String code = (random.nextInt(9000) + 1000) + "";
            //发短信
            SendSmsRequest smsRequest = new SendSmsRequest();
            smsRequest.setPhoneNumbers(phone);
            smsRequest.setSignName("阿里云短信测试");
            smsRequest.setTemplateCode("SMS_154950909");
            smsRequest.setTemplateParam("{\"code\":\"" + code + "\"}\n");
            //5.存储到redis
            redisTemplate.opsForValue().set(key, code, RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);

            client.sendSms(smsRequest);

    }

    @Override
    public String login(LoginVo loginVo) {
        //登录，先做判断
        if(loginVo.getPhone().isEmpty()&&loginVo.getPhone().isBlank()){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        if(loginVo.getCode().isEmpty()&&loginVo.getCode().isBlank()){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        String code= (String) redisTemplate.opsForValue().get(RedisConstant.APP_LOGIN_PREFIX+loginVo.getPhone());
        if (code==null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
        if(!code.equals(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        //让他登录并发token
        LambdaQueryWrapper<UserInfo> userInfoLambdaQueryWrapper=new LambdaQueryWrapper<>();
        userInfoLambdaQueryWrapper.eq(UserInfo::getPhone,loginVo.getPhone());
        UserInfo userInfo = userInfoService.getOne(userInfoLambdaQueryWrapper);
        //数据库没有该用户，新建一个
        if (userInfo==null){
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("佚名"+loginVo.getPhone().substring(5));
            userInfoService.save(userInfo);
        }
        //4.判断用户是否被禁
        if (userInfo.getStatus().equals(BaseStatus.DISABLE)) {
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        System.out.println("userInfo = " + userInfo);
        return JwtUtil.createToken(userInfo.getId(), loginVo.getPhone());
    }
}